<template>
	<view class="content">

		<u-toast ref="uToast"></u-toast>
		<!-- 回到上方按钮 -->
		<u-back-top :scroll-top="scrollTop"></u-back-top>

		<view style="display: flex;align-items: center;">
			<u-search placeholder="请输入商品名称" v-model="searchForm.keyword" @search="search" :showAction="false"
				:clearabled="true">
			</u-search>
			<text class="iconfont" style="font-size: 35px;" @click="selectCategory()">&#xe622;</text>
		</view>
		<u-row customStyle="margin-top: 10px" gutter="20rpx" align="start"
			v-if="(productList[0].length>0||productList[1].length>0)&&loadData==false">
			<u-col span="6" class="col">
				<view id="view1">
					<view class="productVoItem" v-for="(productVo,index1) in productList[0]" :key="index1"
						@click="seeProductDetail(productVo)">
						<u--image v-if="productVo.picList!=null&&productVo.picList.length>0" :showLoading="true"
							:src="urlConstruct(productVo.picList[0].address)" width="100%"
							:height="productVo.picList[0].aspectRatio*100+'%'" radius="10" mode="widthFix"
							:lazy-load="true" :fade="true" duration="450"
							@error="reloadPir(productVo.picList[0].address)">
							<!-- 加载失败展示 -->
							<view slot="error" style="font-size: 24rpx;">加载失败</view>
							<!-- 加载中提示 -->
							<template v-slot:loading>
								<view style="height: 100px;width: 100%;">
									<u-loading-icon color="#A2A2A2"></u-loading-icon>
								</view>
							</template>
						</u--image>
						<!-- <u--image v-else :showLoading="true" :src="src" @click="click"></u--image> -->
						<view class="productMes">
							<text class="productName">【{{productVo.name}}】</text>
							<text>
								{{productVo.description==null?'':productVo.description}}
							</text>
						</view>
						<view style="display: flex;align-items: center;">
							<!-- 现价 -->
							<view class="price">¥<text class="number">{{productVo.price}}</text>/{{productVo.unit}}
							</view>
							<view style="width: 10px;"></view>
							<!-- 原价 -->
							<view class="originPrice">¥{{productVo.originalPrice}}/{{productVo.unit}}
							</view>
						</view>
						<view style="display: flex;align-items: center;">
							<u--image :src="urlConstruct(productVo.avatar)" width="20" height="20"
								shape="circle"></u--image>
							<view style="width: 5px;"></view>
							<view style="font-size: 30rpx;"> {{productVo.nickname}}</view>
						</view>
					</view>
				</view>
			</u-col>
			<u-col span="6" class="col">
				<view id="view2">
					<view class="productVoItem" v-for="(productVo,index1) in productList[1]" :key="index1"
						@click="seeProductDetail(productVo)">
						<u--image v-if="productVo.picList!=null&&productVo.picList.length>0" :showLoading="true"
							:src="urlConstruct(productVo.picList[0].address)" width="100%"
							:height="productVo.picList[0].aspectRatio*100+'%'" radius="10" mode="widthFix"
							:lazy-load="true" :fade="true" duration="450"
							@error="reloadPir(productVo.picList[0].address)">
							<!-- 加载失败展示 -->
							<view slot="error" style="font-size: 24rpx;">加载失败</view>
							<!-- 加载中提示 -->
							<template v-slot:loading>
								<view style="height: 100px;width: 100%;">
									<u-loading-icon color="#A2A2A2"></u-loading-icon>
								</view>
							</template>
						</u--image>
						<!-- <u--image v-else :showLoading="true" :src="src" @click="click"></u--image> -->
						<view class="productMes">
							<text class="productName">【{{productVo.name}}】</text>
							<text>
								{{productVo.description==null?'':productVo.description}}
							</text>
						</view>
						<view style="display: flex;align-items: center;">
							<!-- 现价 -->
							<view class="price">¥<text class="number">{{productVo.price}}</text>/{{productVo.unit}}
							</view>
							<view style="width: 10px;"></view>
							<!-- 原价 -->
							<view class="originPrice">¥{{productVo.originalPrice}}/{{productVo.unit}}
							</view>
						</view>
						<view style="display: flex;align-items: center;">
							<u--image :src="urlConstruct(productVo.avatar)" width="20" height="20"
								shape="circle"></u--image>
							<view style="width: 5px;"></view>
							<view style="font-size: 30rpx;"> {{productVo.nickname}}</view>
						</view>
					</view>
				</view>
			</u-col>
		</u-row>
		<!-- 显示加载相关字样 -->
		<u-loadmore v-if="productList[0].length>0&&loadData==false" :status="loadmoreStatus" />

		<u-empty v-if="productList[0].length==0&&loadData==false" mode="data" icon="http://cdn.uviewui.com/uview/empty/list.png" texColor="#ffffff" iconSize="150"
			iconColor="#D7DEEB" text="当前分类或校区没有商品" textColor="#D7DEEB" textSize="18" marginTop="30">
		</u-empty>
		<view style="margin-top: 20px;" v-if="loadData==true">
			<u-skeleton :loading="true" :animate="true" rows="10"></u-skeleton>
		</view>

		<!-- 浮动按钮 -->
		<FloatButton @click="cellMyProduct()">
			<u--image :src="floatButtonPic" shape="circle" width="60px" height="60px"></u--image>
		</FloatButton>
	</view>
</template>

<script>
	import FloatButton from "@/components/FloatButton/FloatButton.vue";
	import {
		listProductVo
	} from "@/api/market/product.js";
	import pictureApi from "@/utils/picture.js";
	import Vue from 'vue';
	import {
		debounce
	} from "@/utils/debounce.js";
	import store from '@/store/index.js';
	import websocketApi from "@/utils/websocket";
	import {
		picUrlConstruct
	} from "@/utils/picUrlConstruct.js";

	export default {
		components: {
			FloatButton
		},
		onShow: function() {
			let categoryNameList = uni.getStorageSync("categoryNameList");
			if (categoryNameList) {
				this.categoryNameList = categoryNameList;
				this.searchForm.productCategoryId = uni.getStorageSync("productCategoryId");
				this.searchForm.keyword = this.getCategoryLayerName(this.categoryNameList);
				uni.removeStorageSync("categoryNameList");
				uni.removeStorageSync("productCategoryId");
				this.clearResult();
				this.listProductVo().then(() => {
					this.loadData = false;
				});
			}
		},
		data() {
			return {
				title: 'Hello',
				// 浮动按钮的图片
				floatButtonPic: require("@/static/cellLeaveUnused.png"),
				searchForm: {
					// 商品搜索关键词
					keyword: "",
					productCategoryId: undefined,
					sumAspectRatioOfColumn1: 0,
					sumAspectRatioOfColumn2: 0,
					// 标题、价格、头像的高宽比 分子、分母的单位都是rpx
					messageAspectRatio: (30 + 40 + 32) / ((750 - 20 * 2 - 20) / 2)
				},
				productList: [
					[],
					[]
				],
				loadData: false,
				// 用来锁定，防止多次同时进行websocket连接
				lockReconnect: false,
				// 心跳一次间隔的时间，单位毫秒
				heartbeatTime: 5000,
				page: {
					pageNum: 1,
					pageSize: 10
				},
				// 总数据条数
				total: 0,
				// 数据加载状态
				loadmoreStatus: "loadmore",
				// 用来控制滚动到最上方
				scrollTop: 0,
				// 分别存储两列的高宽比总和
				sumAspectRatioOfColumn1: 0,
				sumAspectRatioOfColumn2: 0,
			}
		},
		onLoad() {

		},
		created() {
			// this.initWebsocket();
			// this.$webSocketService.initWebsocket(this.$store, this.Constant);
			// this.getMoreProductVo = debounce(this.getMoreProductVo);
		},
		mounted() {
			this.loadData = true;
			this.listProductVo().then(() => {
				this.loadData = false;
			});
		},
		// 监听用户滑动到底部
		onReachBottom() {
			this.getMoreProductVo();
		},
		// 在滑动过程实时获取现在的滚动条位置，并保存当前的滚动条位置
		onPageScroll(e) {
			this.scrollTop = e.scrollTop;
		},
		methods: {
			urlConstruct(url) {
				return picUrlConstruct(url);
			},
			clearResult() {
				this.productList[0] = [];
				this.productList[1] = [];
				this.sumAspectRatioOfColumn1 = 0;
				this.sumAspectRatioOfColumn2 = 0;
				this.loadData = true;
			},
			/**
			 * 搜索商品
			 */
			search() {
				this.clearResult();
				this.searchForm.productCategoryId = undefined;
				this.listProductVo().then(() => {
					this.loadData = false;
				});
			},
			/**
			 * 查询商品vo集合
			 */
			listProductVo() {
				return new Promise((resolve, reject) => {
					// 设置当前两列的高宽比总和
					// console.log("this.searchForm:" + JSON.stringify(this.searchForm));
					listProductVo(this.searchForm, this.page).then(res => {
						this.total = res.data.pageMes.total;
						let productVoList = res.data.pageMes.rows;
						let groups = res.data.groups;
						for (var i = 0; i < groups[0].length; i++) {
							if (groups[0][i].picList != null && groups[0][i].picList.length > 0) {
								this.sumAspectRatioOfColumn1 += groups[0][i].picList[0].aspectRatio;
							}
							this.productList[0].push(groups[0][i]);
						}
						for (var i = 0; i < groups[1].length; i++) {
							if (groups[1][i].picList != null && groups[1][i].picList.length > 0) {
								this.sumAspectRatioOfColumn2 += groups[1][i].picList[0].aspectRatio;
							}
							this.productList[1].push(groups[1][i]);
						}
						// this.productList[0] = this.productList[0].concat(groups[0]);
						// this.productList[1] = this.productList[1].concat(groups[1]);
						// console.log("this.productList[0]：" + JSON.stringify(this.productList[0]));
						// console.log("this.productList[1]：" + JSON.stringify(this.productList[1]));
						resolve();
					})
				})
			},
			/**
			 * 获取下一页的商品
			 */
			getMoreProductVo() {
				if (this.productList[0].length + this.productList[1].length >= this.total) {
					// this.$refs.uToast.show({
					// 	type: 'warning',
					// 	message: "已经加载完所有商品数据",
					// 	duration: 1000
					// })
				} else {
					if (this.loadData != true) {
						// console.log("--------------------------获取下一页商品---------------------------")
						this.page.pageNum++;
						// 显示正在加载
						this.loadmoreStatus = "loading";
						this.setParam().then(res => {
							this.listProductVo().then(() => {
								if (this.productList[0].length + this.productList[1].length >= this
									.total) {
									// 没有更多了
									this.loadmoreStatus = "nomore";
								} else {
									// 加载更多
									this.loadmoreStatus = "loadmore";
								}
							});
						})
					}
				}
			},
			/**
			 * 设置高宽比参数
			 */
			setParam() {
				return new Promise((resolve, reject) => {
					// select中的参数就如css选择器一样选择元素
					uni.createSelectorQuery().in(this).select("#view1")
						.boundingClientRect((rect) => {
							console.log("rect:" + JSON.stringify(rect));
							//拿到聊天框的高度
							this.searchForm.sumAspectRatioOfColumn1 = rect.height * 1.0 / rect.width;

							uni.createSelectorQuery().in(this).select("#view2")
								.boundingClientRect((rect) => {
									//拿到聊天框的高度
									this.searchForm.sumAspectRatioOfColumn2 = rect.height * 1.0 / rect
										.width;
									resolve();
								})
								.exec();
						})
						.exec();
				})

			},
			/**
			 * 跳转到卖闲置页面
			 */
			cellMyProduct() {
				console.log("我要卖闲置");
				uni.navigateTo({
					url: "/pages/sellMyProduct/sellMyProduct"
				})
			},
			/**
			 * 获取高宽比 乘以 100%
			 */
			getAspectRatio(url) {
				return pictureApi.getAspectRatio(url);
			},
			/**
			 * 选择分类
			 */
			selectCategory() {
				uni.navigateTo({
					url: "/pages/sellMyProduct/selectCategory"
				})
			},
			/**
			 * 获取商品名称
			 */
			getCategoryLayerName() {
				let str = '';
				for (let i = 0; i < this.categoryNameList.length - 1; i++) {
					str += this.categoryNameList[i] + '/';
				}
				return str + this.categoryNameList[this.categoryNameList.length - 1];
			},
			/**
			 * 查看商品的详情
			 */
			seeProductDetail(productVo) {
				// console.log("productVo:"+JSON.stringify(productVo))
				uni.navigateTo({
					url: "/pages/product/detail?productVo=" + encodeURIComponent(JSON.stringify(productVo))
				})
			},
			/**
			 * 重新加载图片
			 */
			reloadPir(pic) {
				console.log("图片加载失败，pic：" + pic)
			},
		}
	}
</script>

<style lang="scss">
	.content {
		padding: 20rpx;

		.col {
			width: 50%;
		}

		.productVoItem {
			margin-bottom: 20px;

			.productMes {
				overflow: hidden;
				text-overflow: ellipsis;
				display: -webkit-box;
				/* 显示2行 */
				-webkit-line-clamp: 1;
				-webkit-box-orient: vertical;
				font-size: 32rpx;

				.productName {
					font-weight: bold;
				}
			}

			.price {
				color: #F84442;
				font-weight: bold;

				.number {
					font-size: 40rpx;
				}
			}

			.originPrice {
				color: #A2A2A2;
				font-size: 15px;
				// 给文字添加中划线
				text-decoration: line-through;
			}
		}
	}
</style>